package top.hypnos.bigdata.filesystem;

import top.hypnos.bigdata.filesystem.command.CommandException;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class MemDatabase {

    private MemDataTree tree;

    private final Snapshot snapshot;

    public MemDatabase(final File basePath) throws IOException {
        final var binLog = new FileBinLog(new File(basePath, "/binlog"));
        this.tree = new MemDataTree(binLog);
        this.snapshot = new FileSnapshot(new File(basePath, "/snapshot"), binLog);
    }

    public MemDataNode getNode(final String path) {
        return tree.getNode(path);
    }

    public int createNode(final String path, final String data) throws InterruptedException, ExecutionException {
        return tree.createNode(path, data);
    }

    public int createNode(final String path, final byte[] data) throws InterruptedException, ExecutionException {
        return tree.createNode(path, data);
    }

    public int deleteNode(final String path) throws InterruptedException, ExecutionException {
        return tree.deleteNode(path);
    }

    /**
     * 保存内存数据快照
     */
    public void snapshot() throws IOException {
        snapshot.save(tree);
    }

    public void recover() throws IOException, CommandException {
        tree = snapshot.recover();
    }
}
